<?php
/**
 * Created by 无所谓已
 * User: Administrator
 * Date: 2025-08-17
 * Time: 20:45
 */

namespace plugin\csauto\app\controller;

use plugin\csauto\app\common\BaseController;
use plugin\csauto\app\model\DownloaderModel;
use plugin\csauto\app\service\ApiWorkService;
use plugin\csauto\app\service\QBittorrentService;
use support\Request;
use support\Response;

class DownloaderController extends BaseController
{

    /**
     * @var DownloaderModel
     */
    protected $model = null;

    /**
     * 构造函数
     *
     * @return void
     */
    public function __construct()
    {
        $this->model = new DownloaderModel;
    }

    public function index(Request $request)
    {
        return view('downloader/index');
    }


    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            /*测试一下下载器的联通*/
            $checkQb = QBittorrentService::checkService($request);
            if (!$checkQb) return $this->fail('下载器连接失败');
            if (!ApiWorkService::checkApi("http://{$request->input('d_host')}:{$request->input('w_port')}/api/checkApi")) {
                return $this->fail('API服务连接失败');
            }
            return parent::insert($request);
        }
        return view('downloader/insert');
    }


    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $checkQb = QBittorrentService::checkService($request);
            if (!$checkQb) return $this->fail('下载器连接失败');
            if (!ApiWorkService::checkApi("http://{$request->input('d_host')}:{$request->input('w_port')}/api/checkApi")) {
                return $this->fail('API服务连接失败');
            }
            return parent::update($request);
        }
        return view('downloader/update');
    }

    public function delete(Request $request): Response
    {
        $ids = $this->deleteInput($request);
        // 子规则一起删除
        $delete_ids = $children_ids = $ids;
        while ($children_ids) {
            $children_ids = $this->model->whereIn('pid', $children_ids)->pluck('id')->toArray();
            $delete_ids = array_merge($delete_ids, $children_ids);
        }
        $this->doDelete($delete_ids);
        return $this->json(0);
    }

    /**
     * 查询后置方法：为每个下载器添加实际任务限制
     * @param array $items
     * @return array
     */
    protected function afterQuery($items)
    {
        foreach ($items as $item) {
            // 添加实际任务限制字段
            $item->effective_task_limit = $item->getEffectiveTaskLimit();
        }
        return $items;
    }
}